package com.hzh.homeWork

import scala.io.Source

object DemoWork3 {
  def main(args: Array[String]): Unit = {
    /**
     * 统计总分年级排名前十学生各科的分数
     */
    //读取文件
    val lines: List[String] = Source.fromFile("data/score.txt").getLines().toList
    //2、过滤脏数据
    val filterList: List[String] = lines.filter((line: String) => {
      val length: Int = line.split(",").length
      length == 3
    })
    //3、取出学号和分数
    val idAndScore: List[(String, Int)] = filterList.map(line => {
      val split: Array[String] = line.split(",")
      //学号
      val id: String = split.head
      //分数
      val score: Int = split.last.toInt
      (id, score)
    })
    //4、按照学号分组
    val groupByList: Map[String, List[(String, Int)]] = idAndScore.groupBy(kv => kv._1)
    //map
    val sumScoList: List[(String, Int, List[(String, Int)])] = groupByList.map {
      case (id: String, list: List[(String, Int)]) =>
        //一个学生所有的分数
        val scores: List[Int] = list.map { case (_, sco: Int) => sco }
        //求总分
        val sumSco: Int = scores.sum
        (id, sumSco,list)
    }.toList
    //按照总分排序，取前10
    val sortByStd: List[(String, Int, List[(String, Int)])] = sumScoList.sortBy(kv => -kv._2)
    //取前10
    val top10: List[(String, Int, List[(String, Int)])] = sortByStd.take(10)
    top10.foreach(println)
  }
}
